package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.DocumentExcerpts;
import cn.stylefeng.guns.modular.business.enums.DocumentExcerptsExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.DocumentExcerptsMapper;
import cn.stylefeng.guns.modular.business.pojo.DocumentExcerptsRequest;
import cn.stylefeng.guns.modular.business.service.DocumentExcerptsService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文献节选信息表业务实现层
 *
 * @author zhangyaowen
 * @date 2021/10/28 16:51
 */
@Service
public class DocumentExcerptsServiceImpl extends ServiceImpl<DocumentExcerptsMapper, DocumentExcerpts> implements DocumentExcerptsService {

    @Resource
    private SubUseBrowseService subUseBrowseService;
    @Resource
    private LoginUserApi loginUserApi;

	@Override
    public void add(DocumentExcerptsRequest documentExcerptsRequest) {
        DocumentExcerpts documentExcerpts = new DocumentExcerpts();
        BeanUtil.copyProperties(documentExcerptsRequest, documentExcerpts);
        this.save(documentExcerpts);
    }

    @Override
    public void del(DocumentExcerptsRequest documentExcerptsRequest) {
        DocumentExcerpts documentExcerpts = this.queryDocumentExcerpts(documentExcerptsRequest);
        this.removeById(documentExcerpts.getId());
    }

    @Override
    public void edit(DocumentExcerptsRequest documentExcerptsRequest) {
        DocumentExcerpts documentExcerpts = this.queryDocumentExcerpts(documentExcerptsRequest);
        BeanUtil.copyProperties(documentExcerptsRequest, documentExcerpts);
        this.updateById(documentExcerpts);
    }

    @Override
    public DocumentExcerpts detail(DocumentExcerptsRequest documentExcerptsRequest) {
        return this.queryDocumentExcerpts(documentExcerptsRequest);
    }

    @Override
    public PageResult<DocumentExcerpts> findPage(DocumentExcerptsRequest documentExcerptsRequest) {
        LambdaQueryWrapper<DocumentExcerpts> wrapper = createWrapper(documentExcerptsRequest);
        Page<DocumentExcerpts> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(sysRolePage);
    }

    @Override
    public List<DocumentExcerpts> findList(DocumentExcerptsRequest documentExcerptsRequest) {
        LambdaQueryWrapper<DocumentExcerpts> wrapper = this.createWrapper(documentExcerptsRequest);
        return this.list(wrapper);
    }

    @Override
    public PageResult<Map<String,Object>>  findExcerpts(String excerptsDoc) {
	    DocumentExcerptsRequest documentExcerptsRequest = new DocumentExcerptsRequest();
	    documentExcerptsRequest.setExcerptsFrom(excerptsDoc);
        LambdaQueryWrapper<DocumentExcerpts> wrapper = this.createWrapperByExcerptsDoc(documentExcerptsRequest);
        Page<DocumentExcerpts> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);
        PageResult<DocumentExcerpts> documentExcerptsPageResult = PageResultFactory.createPageResult(sysRolePage);
        List<DocumentExcerpts> documentExcerptsList=documentExcerptsPageResult.getRows();
        List<Map<String,Object>> mapList=new ArrayList<>();
        PageResult<Map<String,Object>> pageResult = new PageResult<>();
        for(DocumentExcerpts documentExcerpts:documentExcerptsList){
            Map<String, Object> map = new HashMap<String, Object>();
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.JXWX+documentExcerpts.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            map.put("title",documentExcerpts.getExcerptsTitle());
            map.put("annalsfrom",documentExcerpts.getDocAnnalsfrom());
            mapList.add(map);

        }
        pageResult.setRows(mapList);
        pageResult.setPageSize(documentExcerptsPageResult.getPageSize());
        pageResult.setPageNo(documentExcerptsPageResult.getPageNo());
        pageResult.setTotalPage(documentExcerptsPageResult.getTotalPage());
        pageResult.setTotalRows(documentExcerptsPageResult.getTotalRows());
        return pageResult;
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/10/28 16:51
     */
    private DocumentExcerpts queryDocumentExcerpts(DocumentExcerptsRequest documentExcerptsRequest) {
        DocumentExcerpts documentExcerpts = this.getById(documentExcerptsRequest.getId());
        if (ObjectUtil.isEmpty(documentExcerpts)) {
            throw new ServiceException(DocumentExcerptsExceptionEnum.DOCUMENTEXCERPTS_NOT_EXISTED);
        }
        return documentExcerpts;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/10/28 16:51
     */
    private LambdaQueryWrapper<DocumentExcerpts> createWrapper(DocumentExcerptsRequest documentExcerptsRequest) {
        LambdaQueryWrapper<DocumentExcerpts> queryWrapper = new LambdaQueryWrapper<>();

        Long id = documentExcerptsRequest.getId();
        String excerptsSecond = documentExcerptsRequest.getExcerptsSecond();
        String excerptsThird = documentExcerptsRequest.getExcerptsThird();
        String excerptsDoc = documentExcerptsRequest.getExcerptsDoc();
        String excerptsInfo = documentExcerptsRequest.getExcerptsInfo();
        String excerptsFrom = documentExcerptsRequest.getExcerptsFrom();
        String docAnnalsfrom = documentExcerptsRequest.getDocAnnalsfrom();
        String docAnnalspage = documentExcerptsRequest.getDocAnnalspage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), DocumentExcerpts::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(excerptsSecond), DocumentExcerpts::getExcerptsSecond, excerptsSecond);
        queryWrapper.like(ObjectUtil.isNotEmpty(excerptsThird), DocumentExcerpts::getExcerptsThird, excerptsThird);
        queryWrapper.like(ObjectUtil.isNotEmpty(excerptsDoc), DocumentExcerpts::getExcerptsDoc, excerptsDoc);
        queryWrapper.like(ObjectUtil.isNotEmpty(excerptsInfo), DocumentExcerpts::getExcerptsInfo, excerptsInfo);
        queryWrapper.like(ObjectUtil.isNotEmpty(excerptsFrom), DocumentExcerpts::getExcerptsFrom, excerptsFrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(docAnnalsfrom), DocumentExcerpts::getDocAnnalsfrom, docAnnalsfrom);
        queryWrapper.like(ObjectUtil.isNotEmpty(docAnnalspage), DocumentExcerpts::getDocAnnalspage, docAnnalspage);

        return queryWrapper;
    }

    private LambdaQueryWrapper<DocumentExcerpts> createWrapperByExcerptsDoc(DocumentExcerptsRequest documentExcerptsRequest) {
        LambdaQueryWrapper<DocumentExcerpts> queryWrapper = new LambdaQueryWrapper<>();

        Long id = documentExcerptsRequest.getId();
        String excerptsFrom = documentExcerptsRequest.getExcerptsFrom();

        queryWrapper.eq(ObjectUtil.isNotNull(id), DocumentExcerpts::getId, id);
        queryWrapper.eq(ObjectUtil.isNotEmpty(excerptsFrom), DocumentExcerpts::getExcerptsFrom, excerptsFrom);

        return queryWrapper;
    }

    @Override
    public Map<String, Object> toReview(String jmId) {
        byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmId, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.JXWX,false);
        if ("".equals(id)) {
            Map<String, Object> mapLists = new HashMap<>();
            return mapLists;
        }
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {
            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(DocumentExcerptsExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<DocumentExcerpts> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(ObjectUtil.isNotEmpty(id), DocumentExcerpts::getId, id);
        List<DocumentExcerpts> documentExcerptsList = this.list(queryWrapper);

        List<Map<String, Object>> mapList = new ArrayList<>();
        for (DocumentExcerpts documentExcerpts : documentExcerptsList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(documentExcerpts), Map.class);

            // 获取类的属性
            Field[] declaredFields = DocumentExcerpts.class.getDeclaredFields();
            List<Map<String, Object>> mplist = new ArrayList<>();
            // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
            if (declaredFields.length != 0) {
                int i = 1;
                Map<String, Object> p = new HashMap<String, Object>();
                for (Field field : declaredFields) {

                    Map<String, Object> mp = new HashMap<String, Object>();
                    if (field.getAnnotation(ApiModelProperty.class) != null) {
                        //获取注解属性
                        ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                        // key和value可根据需求存
                        // 这存的key为注解的值，value为类属性名

                        if ("excerptsInfo".equals(field.getName()) || "excerptsTitle".equals(field.getName())) {
                            if ("excerptsTitle".equals(field.getName())) {
                                p.put("title", map.get(field.getName()));
                            }else {
                                p.put(field.getName(), map.get(field.getName()));
                            }
                        }
                        else {
                            mp.put("key", aa.value());
                            mp.put("value", map.get(field.getName()));

                            if (i != 1) {
                                mplist.add(mp);
                            }
                        }
                    }
                    i++;
                }
                p.put("list", mplist);
                if (i != 1) {
                    mapList.add(p);
                }
            }
        }
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.YHWXDJ,mapList.get(0).get("title").toString(),userid,request);
        }

        return mapList.get(0);
    }

}